import { defineFakeRoute } from "vite-plugin-fake-server/client";
import { faker } from "@faker-js/faker/locale/zh_CN";
import dayjs from "dayjs";
import { ref } from "vue";

function getPastDate(days: number) {
  return dayjs().subtract(days, "day").format("YYYY-MM-DD");
}

export const msgData = ref<any[]>([
  {
    id: 1,
    title: "系统消息",
    description: faker.book.series(),
    isRead: false,
    createTime: faker.date.between({ from: getPastDate(1), to: getPastDate(0) })
  },
  {
    id: 2,
    title: "系统消息",
    description: faker.book.series(),
    isRead: false,
    createTime: faker.date.between({ from: getPastDate(2), to: getPastDate(1) })
  },
  {
    id: 3,
    title: "系统消息",
    description: faker.book.series(),
    isRead: true,
    createTime: faker.date.between({ from: getPastDate(6), to: getPastDate(5) })
  },
  {
    id: 4,
    title: "系统消息",
    description: faker.book.series(),
    isRead: true,
    createTime: faker.date.between({
      from: getPastDate(16),
      to: getPastDate(15)
    })
  },
  {
    id: 5,
    title: "系统消息",
    description: faker.book.series(),
    isRead: true,
    createTime: faker.date.between({
      from: getPastDate(116),
      to: getPastDate(115)
    })
  }
]);

export default defineFakeRoute([
  {
    url: "/access/messages",
    method: "get",
    response: () => {
      return {
        success: true,
        message: "操作成功",
        data: {
          totalUnread: msgData.value.filter(item => !item.isRead).length,
          list: msgData.value
        }
      };
    }
  },
  {
    url: "/messages/page",
    method: "post",
    //statusCode: 404,
    response: ({ body }) => {
      return {
        success: true,
        message: "操作成功",
        data: {
          list: msgData.value.slice(
            (body.page - 1) * body.pageSize,
            body.page * body.pageSize
          ),
          total: msgData.value.length,
          pageSize: body.pageSize,
          currentPage: body.page
        }
      };
    }
  },
  {
    url: "/messages/:id/read",
    method: "put",
    response: ({ body, params }) => {
      const msg = msgData.value.find(item => item.id == params.id);
      if (msg) {
        msg.isRead = body.read;
      }
      return {
        success: true,
        message: "操作成功",
        body
      };
    }
  },
  {
    url: "/messages/read",
    method: "put",
    response: () => {
      for (const item of msgData.value) {
        item.isRead = true;
      }
      return {
        success: true,
        message: "操作成功"
      };
    }
  },
  {
    url: "/messages/:id",
    method: "delete",
    statusCode: 404,
    response: () => {
      return {
        success: true,
        message: "操作成功"
      };
    }
  },
  {
    url: "/messages",
    method: "delete",
    response: () => {
      return {
        success: false,
        message: "禁止删除"
      };
    }
  }
]);
